import { defaultParentID } from '@/config';
import api from '@/pages/Organization/DepartmentManagement/request';
import groupBaseApi from '@/pages/Organization/GroupBaseManagement/request';
import subsidiaryBaseApi from '@/pages/Organization/SubsidiaryBaseManagement/request';
import { PlusOutlined } from '@ant-design/icons';
import { DrawerForm, ProForm, ProFormSelect, ProFormText } from '@ant-design/pro-components';
import { FormattedMessage } from '@umijs/max';
import { Button, Form } from 'antd';
import { useMemo, useState } from 'react';
import { useModel } from 'umi';

export type Data = DepartmentManagementApi.InfoResponse;
export type FormConfig = { Component: any; props: Record<string, any> };
export interface Props {
  isEdit?: boolean;
  data?: Data;
  onSuccess?: () => void;
  onCancel?: () => void;
}
const colSpan = 2;
function DepartManagementForm(props: Props) {
  const { data, isEdit = false } = props;
  const { initialState } = useModel('@@initialState');

  const [form] = Form.useForm<Data>();

  const [subsidiaryBaseList, setSubsidiaryBaseList] = useState<
    SubsidiaryBaseManagementApi.InfoResponse[]
  >([]);
  const [info, setInfo] = useState<Partial<DepartmentManagementApi.InfoResponse>>({});

  const subsidiaryBaseListOptions = useMemo(
    () => subsidiaryBaseList.map((item) => ({ label: item.subsidiaryName, value: item.id })),
    [subsidiaryBaseList],
  );

  const formConfig = useMemo(() => {
    const subsidiaryID = {
      Component: ProFormSelect,
      props: {
        name: 'subsidiaryID',
        rules: [{ required: true }],
        width: 'md',
        label: '所属子公司',
        placeholder: '请选择所属子公司',
        options: subsidiaryBaseListOptions,
      },
    };
    const departmentName = {
      Component: ProFormText,
      props: {
        name: 'departmentName',
        rules: [{ required: true }],
        width: 'md',
        label: '部门名称',
        placeholder: '请输入名称',
      },
    };

    const createForm: {
      [key in string]: FormConfig;
    } = { subsidiaryID, departmentName };
    const updateForm: {
      [key in string]: FormConfig;
    } = {
      subsidiaryID,
      departmentName,
    };
    return isEdit ? updateForm : createForm;
  }, [isEdit, subsidiaryBaseListOptions]);
  const drawerFormData = useMemo(() => {
    const data: FormConfig[][] = [];
    const keys = Object.keys(formConfig);
    for (let i = 0; i < keys.length; i++) {
      const key = keys[i];
      const index = Math.floor(i / colSpan);
      if (!data[index]) data[index] = [];
      data[index].push(formConfig[key]);
    }
    return data;
  }, [formConfig]);

  const getAllSubsidiaryBaseList = async () => {
    const list = await subsidiaryBaseApi.getSelectList(initialState?.userInfo?.id);
    setSubsidiaryBaseList(list);
  };
  const onOpenChange = (open: boolean) => {
    if (open) {
      const info = data
        ? isEdit
          ? data
          : { id: '', parentID: data.id }
        : { parentID: defaultParentID };
      setInfo(info);
      form.setFieldsValue(info);
      getAllSubsidiaryBaseList();
    } else {
      setInfo({});
      form.resetFields();
      props.onCancel?.();
    }
  };

  const onSubmit = async (data: Data) => {
    const groupBaseList = await groupBaseApi.getAllList();
    const groupID = groupBaseList[0]?.id || '';
    const { departmentName, subsidiaryID } = data;
    const { id = '', parentID = '' } = info;
    if (isEdit) {
      const params: DepartmentManagementApi.UpdateParams = {
        id,
        parentID,
        departmentName,
        groupID,
        subsidiaryID,
      };
      const data = await api.update(params);
      if (data.success) props.onSuccess?.();
      return data.success;
    } else {
      const params: DepartmentManagementApi.CreateParams = {
        parentID,
        departmentName,
        groupID,
        subsidiaryID,
      };
      const data = await api.create(params);
      if (data.success) props.onSuccess?.();
      return data.success;
    }
  };

  return (
    <DrawerForm
      autoFocusFirstInput
      title={`${isEdit ? '编辑' : '新建'}部门`}
      form={form}
      drawerProps={{ destroyOnClose: true }}
      resize={{
        maxWidth: window.innerWidth * 0.8,
        minWidth: 400,
        onResize() {},
      }}
      trigger={
        isEdit ? (
          <Button type="link">编辑</Button>
        ) : !!data ? (
          <Button type="link">新建</Button>
        ) : (
          <Button type="primary">
            <PlusOutlined /> <FormattedMessage id="pages.searchTable.new" defaultMessage="New" />
          </Button>
        )
      }
      onOpenChange={onOpenChange}
      onFinish={onSubmit}
    >
      {drawerFormData.map((item, i) => {
        return (
          <ProForm.Group key={i}>
            {item.map((data) => {
              const { props, Component } = data;
              return <Component key={props.name} {...props} />;
            })}
          </ProForm.Group>
        );
      })}
    </DrawerForm>
  );
}

export default DepartManagementForm;
